package com.araim.rringtone;

import java.util.ArrayList;
import java.util.Map;
import java.util.Random;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.util.Log;

import com.araim.rringtone.db.RandomRingtoneDatabase;

public class AlarmChanger extends BroadcastReceiver {
	public static final Uri CONTENT_URI = Uri.parse("content://com.htc.android.worldclock/alarm"); // Uri.parse("content://com.android.alarmclock/alarm");

	private void drawAlarm(Context context, int id) {
		SharedPreferences enabledSettigns = context.getSharedPreferences(RandomRingtone.ENABLED_ALARMS, 0);
		boolean defaultAlarm = enabledSettigns.getBoolean("alarm-1", false);
		boolean thisAlarm = enabledSettigns.getBoolean("alarm" + id, false);
		if (!defaultAlarm && !thisAlarm) {
			return;
		}
		Random rr = new Random();

		RandomRingtoneDatabase rdb = new RandomRingtoneDatabase(context);
		ArrayList<RingtoneInfo> rings = rdb.getAllRingtones(RingtoneManager.TYPE_ALARM, defaultAlarm ? -1 : id);

		try {
			Log.d(RandomRingtone.TAG, "Found " + rings.size() + " user selected alarms for ID: " + (defaultAlarm ? -1 : id));
			// do nothing if no ringtone has been selected
			if (rings.size() == 0) {
				return;
			}
			int num = -1;
			do {
				// get a random index
				num = rr.nextInt(rings.size());

				RingtoneInfo ri = rings.get(num);

				// create an uri for the randomly selected alarm (the
				// URI consists of the URI stored in DB + the id of a
				// ringtone)
				// Uri uri = Uri.parse(ri.getUri() + "/" + ri.getId());
				// if this ringtone exists (it might have been removed)

				if (RingtoneInfo.isValidAlarm(context, ri)) {
					Alarm.setAlarmSound(context, id, ri.getFullUri());
					Log.i(RandomRingtone.TAG, "Alarm \"" + ri.getName() + "\" has been set");
					return;
				} else {
					Log.i(RandomRingtone.TAG, "Alarm \"" + ri.getName() + "\" is no longer valid");
					// the ringtone is no longer valid - remove it
					rings.remove(num);
					rdb.delete(ri);
					// if there are no more - don't set
					if (rings.size() == 0) {
						Log.i(RandomRingtone.TAG, "After removing invalid alarms there is not one left");
						return;
					}
				}
			} while (true);
		} catch (Exception e) {
			Log.e(RandomRingtone.TAG, "Error setting alarm: " + e.toString());
		}

		try {
			purgeAlarms(context);
		} catch (Exception e) {
			Log.e(RandomRingtone.TAG, "Error Purging alarms ", e);
		}

	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d(RandomRingtone.TAG, intent.getAction());

		int id = intent.getIntExtra("alarm_id", -1);
		if (id == -1) {
			// HTC alarm :(
			final byte[] data = intent.getByteArrayExtra("intent.extra.alarm_raw");
			id = data[0] + 0xFF * data[1] + 0xFF00 * data[2] + 0xFF0000 * data[3];
		}
		Log.d(RandomRingtone.TAG, "Broadcast received => id: " + id);
		// get the shared preferences for this application
		SharedPreferences settings = context.getSharedPreferences(RandomRingtone.RRINGTONE_PREFS_NAME, 0);
		// check if random ringtone is active

		// if it is...
		if (id > 0) {
			drawAlarm(context, id);
			try {
				// ~50% chance that this has kicked in before the actual allarm,
				// so the alarm will use the newly drawn ringtone
				// if so - draw another one for the next time it rings
				Thread.sleep(1000 * 5);
			} catch (InterruptedException e1) {
				Log.e(RandomRingtone.TAG, "Alarm interrupted...", e1);
			}
			drawAlarm(context, id);
		}
	}

	private void purgeAlarms(Context context) {
		SharedPreferences sPreferences = context.getSharedPreferences(RandomRingtone.ENABLED_ALARMS, 0);
		SharedPreferences.Editor editor = sPreferences.edit();
		RandomRingtoneDatabase db = new RandomRingtoneDatabase(context);
		try {
			Map<String, ?> map = sPreferences.getAll();
			ArrayList<Integer> list = Alarm.getAllAlarmIds(context);
			for (String sAlarm : map.keySet()) {
				if (sAlarm.equals("alarm-1")) {
					continue;
				}
				String sAlarmid = sAlarm.substring(5);
				try {
					int id = Integer.parseInt(sAlarmid);
					if (!list.contains(id)) {
						editor.remove(sAlarm);
						db.clearAlarms(id);
					}
				} catch (Exception e) {
					Log.e(RandomRingtone.TAG, "Invalid alarm ID.", e);
					editor.remove(sAlarm);
				}

			}
		} finally {
			editor.commit();
		}

	}

}
